//
//  RegisterViewController.m
//  yunyan
//
//  Created by haichuang on 2018/4/2.
//  Copyright © 2018年 haichuang. All rights reserved.
//

#import "RegisterViewController.h"
#import "ConfirmViewController.h"
@interface RegisterViewController ()
@property (weak, nonatomic) IBOutlet UITextField *phoneTF;
@property (weak, nonatomic) IBOutlet UITextField *codeTF;
@property (weak, nonatomic) IBOutlet UIButton *completeBtn;
@property (weak, nonatomic) IBOutlet UIButton *codeBtn;

@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    
    if (_isLogin) {
        if (_isRegister) {
            
            [self customNaviItemTitle:@"绑定手机号" isLeft:YES];
        }else{
            
            [self customNaviItemTitle:@"忘记密码" isLeft:YES];
        }
        [_completeBtn setTitle:@"下一步" forState:UIControlStateNormal];
    }else{
        [self customNaviItemTitle:@"绑定手机号" isLeft:YES];
        [_completeBtn setTitle:@"绑定" forState:UIControlStateNormal];
    }
   
}
- (IBAction)obtainCodeBtn:(UIButton *)sender {
    
//    if ([SHJudgeTools valiMobile:self.phoneTF.text] != nil) {
//        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//        hud.mode = MBProgressHUDModeText;
//        hud.margin = 10.f;
//        hud.yOffset = 100.f;
//        hud.labelText = [SHJudgeTools valiMobile:self.phoneTF.text];
//        hud.removeFromSuperViewOnHide = YES;
//        [hud hide:YES afterDelay:0.5];
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [hud removeFromSuperview];
//        });
//        return;
//    }
    
    if (self.phoneTF.text==nil||self.phoneTF.text.length
        !=11) {
        
        SHuiMBhudTextTimeStr(@"请输入正确的手机号");
        return;
    }
    [self sendMSNetWorkingFor];
    
}
- (IBAction)nextBtn:(UIButton *)sender {
    
    if (_isLogin) {
        
        if (self.phoneTF.text==nil||self.phoneTF.text.length
            !=11) {
            
            SHuiMBhudTextTimeStr(@"请输入正确的手机号");
            return;
        }
        if (self.codeTF.text==nil||self.codeTF.text.length<=0) {
            
            SHuiMBhudTextTimeStr(@"请输入验证码");
            return;
        }
        
        [self veCodeRequest];
    }else{
        if (self.phoneTF.text==nil||self.phoneTF.text.length
            !=11) {
            
            SHuiMBhudTextTimeStr(@"请输入正确的手机号");
            return;
        }
        if (self.codeTF.text==nil||self.codeTF.text.length<=0) {
            
            SHuiMBhudTextTimeStr(@"请输入验证码");
            return;
        }
        
        [self veCodeRequest];
    }
    
  
}

// 验证码
-(void)sendMSNetWorkingFor{
    
    NSString * type;
    if (_isLogin) {
        if (_isRegister) {
            
            type = @"1";
        }else{
            
            type = @"2";
        }
    }else{
        type = @"3";
    }
    NSDictionary * dic = @{@"mobile":self.phoneTF.text,
                           @"type":type
                           };
    
//    NSString * parametersStr = [NSString stringWithFormat:@"%@%@?uphone=%@&ver=%@",address_url,regin_sms_api,_phoneText.text,md5ver];
    
//    NSLog(@"parametersStr = %@",parametersStr);
//    SHuiMBhubNoTimeStr(@"正在发送");
    [PostNetWorking postNetWorkingStr:RequestUrlStr(get_code_api) andparameters:dic Success:^(id responseObject) {
        
        __block int timeout = 60; //倒计时时间
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
        dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
        dispatch_source_set_event_handler(_timer, ^{
            if(timeout<=1){
                dispatch_source_cancel(_timer);
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    [self.codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
                    self.codeBtn.userInteractionEnabled = YES;
                });
            }else{
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    NSString  * time = [NSString stringWithFormat:@"%d(秒)",timeout];
                    [UIView beginAnimations:nil context:nil];
                    [UIView setAnimationDuration:1];
                    [self.codeBtn setTitle:time forState:UIControlStateNormal];
                    [UIView commitAnimations];
                    self.codeBtn.userInteractionEnabled = NO;
                });
                timeout--;
            }
        });
        dispatch_resume(_timer);
        
        
    } failed:^(NSURLSessionDataTask * _Nullable task, NSError *error) {
        
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        
        NSLog(@"responses.code = %ld",responses.statusCode);
        
        if (responses.statusCode == 400) {
            if ([type isEqualToString:@"2"]) {
            SHuiMBhudTextTimeStr(@"该手机号码未注册");
            }else {
            SHuiMBhudTextTimeStr(@"手机号已被注册！");
            }
        }else if (responses.statusCode == 502){
            SHuiMBhudTextTimeStr(@"不能与原密码相同");
        }else {
            SHuiMBhudTextNetError;
        }
    }];
    
}

-(void)veCodeRequest{
    
    NSString * type;
    if (_isLogin) {
        if (_isRegister) {
            
            type = @"1";
        }else{
            
            type = @"2";
        }
    }else{
        type = @"3";
    }
    
    NSString * parametersStr = [NSString stringWithFormat:@"%@%@",address_url,verify_code_api];
    NSDictionary * parameter = @{@"mobile":self.phoneTF.text,
                                 @"type":type,
                                 @"code":self.codeTF.text
                                 };
    
    [PostNetWorking postNetWorkingStr:parametersStr  andparameters:parameter  Success:^( id  responseObject) {
        SHuiMBHidleYes;
        
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW , (1 * NSEC_PER_SEC)), dispatch_get_main_queue(),^{
                
                ConfirmViewController * confirmVC = [[ConfirmViewController alloc]init];
                confirmVC.mobileStr = self.phoneTF.text;
                confirmVC.codeStr = self.codeTF.text;
                
                if (_isLogin) {
                    if (_isRegister) {
                        confirmVC.isRegister = YES;
                        confirmVC.isLogin = YES;
                        if (_isPhone) {
                            
                            confirmVC.isPhone = YES;
                        }else {
                            
                            confirmVC.isPhone = NO;
                        }
                    }else{
                        confirmVC.isRegister = NO;
                        confirmVC.isLogin = YES;
                    }
                }else{
                    
                    confirmVC.isRegister = NO;
                    confirmVC.isLogin = NO;
                }
              
                [self.navigationController pushViewController:confirmVC animated:YES];
            });
        });
        
    } failed:^(NSURLSessionDataTask * _Nullable task,NSError *error) {

        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        if (responses.statusCode == 404) {
            SHuiMBhudTextTimeStr(@"验证码不正确");
        }else {
            SHuiMBhudTextNetError;
        }
    }];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
